/**
 * 叠加接头icon到电缆井icon上
 * @param { HTMLImageElement } cableWellIcon
 */
export function overlapConnectorIcon(cableWellIcon) {
  return loadBitmap('cableConnector.png').then((cableConnectorIcon) => {
    const canvas = document.createElement('canvas')
    canvas.width = cableWellIcon.width
    canvas.height = cableWellIcon.height
    const ctx = canvas.getContext('2d')
    ctx.scale(1, 1)
    ctx.drawImage(cableWellIcon, 0, 0)
    ctx.drawImage(cableConnectorIcon, 6, 6, 20, 20)
    return new Promise((resolve, reject) => {
      const newImage = new Image()
      const dataUrl = canvas.toDataURL()
      newImage.src = dataUrl
      newImage.onload = function (img) {
        resolve(newImage)
      }
      newImage.onerror = function (e) {
        reject(e)
      }
    })
  })
}

export function replaceImageColor(color = '#000000', image) {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height

    const ctx = canvas.getContext('2d')
    ctx.scale(1, 1)
    ctx.drawImage(image, 0, 0)
    ctx.globalCompositeOperation = 'multiply'
    ctx.fillStyle = color
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.globalCompositeOperation = 'destination-in'
    ctx.drawImage(image, 0, 0)

    const newImage = new Image()
    const dataUrl = canvas.toDataURL()
    newImage.src = dataUrl
    newImage.onload = function (img) {
      resolve(newImage)
    }
    newImage.onerror = function (e) {
      reject(e)
    }
  })
}

export function loadBitmap(filename) {
  return new Promise((resolve, reject) => {
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
      // fs.root是根目录操作对象DirectoryEntry
      fs.root.getFile(
        '/static/tuli/' + filename,
        {
          create: true,
        },
        function (fileEntry) {
          fileEntry.file(function (file) {
            var fileReader = new plus.io.FileReader()
            fileReader.readAsDataURL(file)
            fileReader.onloadend = function (e) {
              try {
                const image = new Image()
                image.src = e.target.result
                image.onload = function () {
                  resolve(image)
                }
                image.onerror = function (e) {
                  reject(e)
                }
              } catch (error) {
                console.error(filename + '图片加载失败')
                reject(error)
              }
            }
          })
        }
      )
    })
  })
}
